package com.kexun.lds;

public class Demo1 {

    //不同线程访问不同资源  线程交替进行

    //wait 和  notify 只能在 同步代码块中出现
    public static void main(String[] args) {
        Print p = new Print();
        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    try {
                        p.p1();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    try {
                        p.p2();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}

class Print {

    int i = 1;
    Object obj=new Object();

    public synchronized void p1() throws InterruptedException {

            if (i != 1) {
            this.wait();
        }
            System.out.print("程");
            System.out.print("序");
            System.out.print("猿1");
            System.out.println("");
            i = 2;
            this.notify();

    }

    public synchronized void p2() throws InterruptedException {

        if (i != 2) {
            this.wait();
        }
        System.out.print("攻");
        System.out.print("城");
        System.out.print("狮2");
        System.out.println("");
        i = 1;
        this.notify();
    }
}